# -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 19:55:40 2012

@author: Winand
"""
if __name__ == '__main__': import sys; sys.path.append("C:\\WinPython-32bit-2.7.3.2\\projects\\lancomm")

import urlparse, httplib, Cookie, re, cgi
#from cookielib import LWPCookieJar
from webapi import config
from webapi.general import str8, HtmlProcessor

class RuTracker():
    URL_DL="http://dl.rutracker.org/forum/dl.php?t="
    URL_TOPIC="http://rutracker.org/forum/viewtopic.php?t="
    URL_LOGIN="http://login.rutracker.org/forum/login.php"
    
    def __init__(self, user, passw):
        self.user=user
        self.passw=passw
        self.cookie=config.cget("rutracker/cookie")
        
    def __needLogin(f): #@decorator
        def func(self, *args, **kwargs):
            loggedin = True
            if not self.__checkAuth(): loggedin=self.__authenticate()
            if loggedin: return f(self, *args, **kwargs)
            else: print "You are not logged in"
        return func
        
    def __authenticate(self):
        x=self.__login(self.user, self.passw)
        self.cookie=self.__extractCookies(x.getheaders())
        if self.__checkAuth():
            print 'rutracker: logged in'
            config.cset("rutracker/cookie", self.cookie)
            return True
        else: print "rutracker: failed to login"
    
    def __url_get_status(self, url):
        headers={"Cookie": self.cookie} if self.cookie else {}
        parsed = urlparse.urlparse(url)
        h = httplib.HTTPConnection(parsed.netloc)
        h.request('HEAD', parsed.path, headers=headers)
        return h.getresponse().status
        
    def __checkAuth(self):
        return self.__url_get_status(self.URL_LOGIN)==302
        
    def __login(self, user, passw):
        headers={"Cookie": self.cookie} if self.cookie else {}
        headers['Content-type'] = "application/x-www-form-urlencoded"
        parsed = urlparse.urlparse(self.URL_LOGIN)
        h = httplib.HTTPConnection(parsed.netloc)
        h.request('POST', parsed.path, \
        "login_username="+user+"&login_password="+passw+ \
        "&ses_short=0&login=%C2%F5%EE%E4", headers)
        return h.getresponse()
        
    def __extractCookies(self, headers):
        lcookie = "\r\n".join([h[1] for h in headers if h[0]=='set-cookie'])
        return "; ".join([k+"="+m.value \
                                for k,m in Cookie.BaseCookie(lcookie).items()])
    
    def __readTopic(self, topic):
        headers={"Cookie": self.cookie} if self.cookie else {}
        parsed = urlparse.urlparse(self.URL_TOPIC+topic)
        h = httplib.HTTPConnection(parsed.netloc)
        h.request('GET', parsed.path+"?"+parsed.query, headers=headers)
        return h.getresponse().read()
    
    #get filename from response, build it if failed
    def __getFilename(self, topic, resp):
        try: return cgi.parse_header(resp.getheader('Content-Type'))[1]['name']
        except: return "[rutracker.org].t"+topic+".torrent"
        
    @__needLogin
    def getTorrentTimestamp(self, url):
        topic=url.split("=")[1] #extract topic number from url
        html=self.__readTopic(topic)
        m = re.search("\\[ (.* [0-9]{1,2}:[0-9]{2}) \\]", html)
        return str8(HtmlProcessor.toSafeText(m.group(1)),'cp1251') if m else None
    
    @__needLogin
    def getTorrentFile(self, topic):
        headers={"Cookie": self.cookie} if self.cookie else {}
        parsed = urlparse.urlparse(self.URL_DL+topic)
        h = httplib.HTTPConnection(parsed.netloc)
        h.request('POST', parsed.path+"?"+parsed.query, headers=headers)
        r=h.getresponse()
        print r.getheaders(), r.status, r.reason
        return r.read(), self.__getFilename(topic, r)
        
    def getTopicName(self, url):
        topic=url.split("=")[1] #extract topic number from url
        html=self.__readTopic(topic)
        m = re.search('<h1 class="maintitle">.+t='+topic+'">(.+)</a></h1>', html)
#        open("c:\\check.txt", 'wb').write(m.group(1)+'\n'+m.group(1).decode("cp1251")+'\n'+m.group(1).decode("cp1251").encode('utf-8'))
        return str8(HtmlProcessor.toSafeText(m.group(1)),'cp1251') if m else None
    
    @staticmethod
    def canHandle(url):
        return True if re.match( \
            "http://rutracker\.org/forum/viewtopic\.php\?t=[0-9]+$", url \
            ) else False
        
if __name__ == '__main__':
    trk=RuTracker("xxxxx", "yyyyy")
    print trk.getTopicName("http://rutracker.org/forum/viewtopic.php?t=3949538")
    print trk.getTorrentTimestamp("http://rutracker.org/forum/viewtopic.php?t=3949538")

#if __name__ == '__main__':
#    trk=RuTracker(TRK_USER, TRK_PASS, COOKIE_FILE)
#    dat, name = trk.getTorrentFile(TRK_TOPIC)
#    print name
#    if dat:
#        try: open(TOR_PATH_OUT+name, 'wb').write(dat)
#        except IOError: print "failed to save torrent file"
#    else: print "failed to get torrent file"

#hs = [('transfer-encoding', 'chunked'), ('set-cookie', 'bb_data=1-7550359-M1EnNZcMNSChA71UtRep-1608349186-1355755366-1355755366-3109931736-1; expires=Tue, 17-Dec-2013 14:42:46 GMT; path=/forum/; domain=.rutracker.org; httponly'), ('server', 'nginx'), ('connection', 'keep-alive'), ('location', 'http://rutracker.org/forum/index.php'), ('date', 'Mon, 17 Dec 2012 14:42:46 GMT'), ('x-frame-options', 'SAMEORIGIN'), ('content-type', 'text/html')]

#print url_get_status("http://login.rutracker.org/forum/login.php")
#
#cj = LWPCookieJar("C:\\cookie.txt")
#try: cj.load()
#except: pass
#urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)))
#
#req=urllib2.Request(url="http://login.rutracker.org/forum/login.php", \
#data="login_username="+TRK_USER+"&login_password="+TRK_PASS+"&ses_short=0&login=%C2%F5%EE%E4", \
#headers={'Content-type': "application/x-www-form-urlencoded"}
#)
##req=urllib2.Request(url="http://ya.ru")
## make the request and print the results
#res = urllib2.urlopen(req)
#res.read()
#for cookie in cj:
#    print cookie
#cj.save()
#
#print url_get_status("http://login.rutracker.org/forum/login.php")